"use strict"
//手机业务

//发送验证码
exports.code = function () {
    let phone = this.get("phone",'string');
    if(!checkPhone(phone)){
        return this.error("phone number error")
    }
    return Promise.resolve().then(()=>{
        return this.library.call(this,"opensdk/handle","code",phone);
    }).then(ret=>{
        let vcodeModel = this.model.redis("vcode",this.branch);
        return vcodeModel.set(phone,ret['obj'],60);
    })
}

exports.changePassWord = function () {
    let code = this.get("code",'string');
    let phone = this.get("phone",'string');
    let password = this.get("password",'string');
    if(!code){
        return this.error("args empty")
    }
    if(!checkPhone(phone)){
        return this.error("phone number error")
    }

    let vcodeModel = this.model.redis("vcode",this.branch);
    return vcodeModel.get(phone).then((ret)=>{
        if(!ret || ret != code){
            return this.error("phone vcode error",code);
        }
    }).then(()=>{
        let opensdk = this.opensdk["_id"];
        let openidModel = this.model.branch("openid",this.branch);
        return openidModel.check(opensdk,phone);
    }).then((data)=>{
        if(!data) {
            return this.error("phone not exist",phone);
        }
        // let members = this.model.admin('members');
        let opensdk = this.opensdk["_id"];
        let openidModel = this.model.branch("openid",this.branch);
        return openidModel.login(opensdk,phone,password,data["guid"]);
    })
}


//登录
exports.login = function () {
    let code = this.get("code",'string');
    let phone = this.get("phone",'string');
    let password = this.get("password",'string');
    if(!code){
        return this.error("args empty")
    }
    if(!checkPhone(phone)){
        return this.error("phone number error")
    }

    let vcodeModel = this.model.redis("vcode",this.branch);
    return vcodeModel.get(phone).then((ret)=>{
        if(!ret || ret != code){
            return this.error("phone vcode error",code);
        }
    }).then(()=>{
        let opensdk = this.opensdk["_id"];
        let openidModel = this.model.branch("openid",this.branch);
        // let members = this.model.admin('members');
        return openidModel.login(opensdk,phone,password);
    })
}



function checkPhone(phone) {
    return /^1[34578]\d{9}$/.test(phone);
}